using System.Net;
using System.Net.Sockets;
using System.Text;
using MultiAgentsShared;

namespace MultiAgentsClient.Tools;

[GptToolSet("Tcp ToolSet", "")]
public class TcpToolProvider
{
    [GptFunc("Execute tcp command and get its outputs. Return the outputs within one second.", true)]
    public static string ExecuteTcpCommand(
        [GptFuncParam("ip address of command")] string ipAddress,
        [GptFuncParam("port of command")] int port,
        [GptFuncParam("command to execute")] string command)
    {
        try
        {
            using TcpClient client = new();
            client.Connect(IPAddress.Parse(ipAddress), port);

            using NetworkStream stream = client.GetStream();
            StringBuilder response = new();

            if (!string.IsNullOrEmpty(command))
            {
                byte[] data = Encoding.ASCII.GetBytes(command + "\n");
                stream.Write(data, 0, data.Length);
                stream.Flush();
            }

            byte[] buffer = new byte[256];
            int bytesRead;

            Thread.Sleep(1000);

            while (stream.DataAvailable)
            {
                bytesRead = stream.Read(buffer, 0, buffer.Length);
                response.Append(Encoding.ASCII.GetString(buffer, 0, bytesRead));
            }

            return response.ToString().Trim();
        }
        catch (Exception)
        {
            return "Execute TCP command failed.";
        }
    }
}
